package implementations;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import global.GlobalVars;
import interfaces.IBoard;
import interfaces.IGamePanel;
import interfaces.IMessageBox;
import interfaces.IPlayer;
import interfaces.IPoint;
import interfaces.IShip;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import serverController.Server;

import clientController.Client;

public class GamePanelImpl extends JFrame implements IGamePanel {


	private static final long serialVersionUID = 1L;
	private IGamePanel gamePanelImpl;
	private JFrame thisFrame;
	private JFrame callerFrame;
	private IPlayer player;
	private JButton[][] myButtons;
	private JButton[][] enemyButtons;
	private Server server;
	private JButton[][] nextShipButtons;
	private JTextArea textArea;


	public GamePanelImpl(JFrame callerFrame, String status, int id, String ip,
			int port) {
		super();
		gamePanelImpl = this;
		if (status == "Create") {
			System.out.println("Gamepanel:IP:" + ip);
			player = new PlayerImpl("Player1", 1, id);
			server = new Server(id, player,gamePanelImpl);
			server.start();
			// Client.createClient(id,"-1");
		} else {
			System.out.println("Gamepanel:IP:" + ip);
			player = new PlayerImpl("Player2", 2, id);
			server = new Server(id, player,gamePanelImpl);
			server.start();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Client.createClient(id, ip, port, player);
		}
		myButtons = new JButton[GlobalVars.gridXSize][GlobalVars.gridYSize];
		enemyButtons = new JButton[GlobalVars.gridXSize][GlobalVars.gridYSize];

		for (int i = 0; i < GlobalVars.gridXSize; i++) {
			for (int j = 0; j < GlobalVars.gridYSize; j++) {
				myButtons[i][j] = new JButton();
				enemyButtons[i][j] = new JButton();
			}
		}
		
		this.callerFrame = callerFrame;
		callerFrame.setVisible(false);
		thisFrame = this;
		thisFrame = new JFrame();
		thisFrame.setBounds(100, 100, 740, 580);
		thisFrame.setVisible(true);
		thisFrame.setLayout(new BorderLayout(10, 10));

		//thisFrame.add(NorthPanel(), BorderLayout.NORTH);
		thisFrame.add(CenterPanel(), BorderLayout.CENTER);
		thisFrame.add(SouthPanel(), BorderLayout.SOUTH);

		thisFrame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				gamePanelImpl.getCallerFrame().setVisible(true);
				super.windowClosed(arg0);
			}
		});
		thisFrame.revalidate();

		callerFrame.setEnabled(true);

	}

//	public static long getSerialversionuid() {
//		return serialVersionUID;
//	}

	public IGamePanel getGamePanelImpl() {
		return gamePanelImpl;
	}

	public JFrame getThisFrame() {
		return thisFrame;
	}

	public JFrame getCallerFrame() {
		return callerFrame;
	}

	public IPlayer getPlayer() {
		return player;
	}

	private Component SouthPanel() {
		String text="CEVA!";
		JPanel panel = new JPanel();
		
		textArea = new JTextArea(text);

		panel.add(textArea);
		return panel;
	}

	private Component CenterPanel() {
		JPanel panel = new JPanel();

		JPanel myBoardPanel = new JPanel(new GridLayout(GlobalVars.gridXSize,
				GlobalVars.gridYSize));
		for (int i = 0; i < GlobalVars.gridXSize; i++) {
			for (int j = 0; j < GlobalVars.gridYSize; j++) {
				myButtons[i][j].setPreferredSize(new Dimension(16, 16));
				final int x = i;
				final int y = j;
				myButtons[i][j].addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						System.out.println("My board: " + x + " " + y);
						if (player.hasPlantableShips()) {
							try {
								
								player.setNextShipOnBoard(new PointImpl(x, y));
								paintMyButtons(player.getMyBoard().getGrid());
								nextShipToBePlanted();
							} catch (Exception e) {
								System.out.println("Exception:"
										+ e.getMessage().toString());
								IMessageBox messageBox = new MessageBoxImpl(e
										.getMessage(), thisFrame);
								e.printStackTrace();

							}
						}
						if (!player.hasPlantableShips()) {
							server.setSvStat(2);
							System.out.println("Game is ready!");
							Client.playerRdy();
						}
						super.mouseClicked(arg0);
					}
				});
				myBoardPanel.add(myButtons[i][j]);

			}
		}

		JPanel enemyBoardPanel = new JPanel(new GridLayout(
				GlobalVars.gridXSize, GlobalVars.gridYSize));
		for (int i = 0; i < GlobalVars.gridXSize; i++) {
			for (int j = 0; j < GlobalVars.gridYSize; j++) {
				enemyButtons[i][j].setPreferredSize(new Dimension(16, 16));
				final int x = i;
				final int y = j;
				enemyButtons[i][j].addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						System.out.println("Enemy board: " + x + " " + y);
						
						if (server.getSvStat() > 1&& server.isOpponentRdy())
						{
							if (server.isYourTurn())
							{
								//textArea.setText("YourTurn");
								Client.clientAttack(player.getId() ,new PointImpl(x, y));
								server.setYourTurn(false);
								paintEnemyButtons(player.getEnemyBoard().getGrid());
								paintMyButtons(player.getMyBoard().getGrid());
								//textArea.setText("EnemyTurn");
								//el
								//mouseClicked();
								
							}
							else
								System.out.println("Not your turn!");
						} else
							System.out.println("You can not attack!");
						
						// TODO: add proper functionality
						super.mouseClicked(arg0);
					}
				});
				enemyBoardPanel.add(enemyButtons[i][j]);

			}
		}

		JPanel myNextShip = new JPanel(new GridLayout(GlobalVars.maxShipLength,
				GlobalVars.maxShipLength));
		nextShipButtons = new JButton[GlobalVars.maxShipLength][GlobalVars.maxShipLength];

		for (int i = 0; i < GlobalVars.maxShipLength; i++) {
			for (int j = 0; j < GlobalVars.maxShipLength; j++) {
				nextShipButtons[i][j] = new JButton();
				nextShipButtons[i][j].setPreferredSize(new Dimension(16, 16));
				final int x = i;
				final int y = j;

				myNextShip.add(nextShipButtons[i][j]);

			}
		}
		nextShipToBePlanted();

		panel.add(myBoardPanel);
		panel.add(enemyBoardPanel);
		panel.add(myNextShip);
		return panel;
	}

	private void nextShipToBePlanted() {
		IShip nextPlantableShip = player.getNextPlantableShip();
		JButton aux=new JButton();
		Color colorDef = aux.getBackground();
		for(int i=0;i<GlobalVars.maxShipLength;i++)
		{
			for(int j=0;j<GlobalVars.maxShipLength;j++)
			{
				nextShipButtons[i][j].setBackground(colorDef);
			}
		}
		
		if (nextPlantableShip != null) {
			nextPlantableShip.setMainPoint(new PointImpl(1, 1));
			nextPlantableShip.setMainPoint(new PointImpl(1, 1));
			ArrayList<IPoint> points = nextPlantableShip.getPoints();
			for (int k = 0; k < points.size(); k++)
				nextShipButtons[points.get(k).getX()][points.get(k).getY()]
						.setBackground(Color.blue);
		}
		
	}

	public void paintMyButtons(char[][] grid) {
		for (int i = 0; i < GlobalVars.gridXSize; i++) {
			for (int j = 0; j < GlobalVars.gridYSize; j++) {
				if (grid[i][j] == GlobalVars.myShipPart)
					myButtons[i][j].setBackground(Color.blue);
				else if (grid[i][j] == GlobalVars.waves)
					myButtons[i][j].setBackground(Color.cyan);
				else if (grid[i][j] == GlobalVars.myShipPartHitted)
					myButtons[i][j].setBackground(Color.red);
				else if (grid[i][j] == GlobalVars.myBoardMiss)
					myButtons[i][j].setBackground(Color.DARK_GRAY);

			}

		}
	}

	public void paintEnemyButtons(char[][] grid) {
		for (int i = 0; i < GlobalVars.gridXSize; i++) {
			for (int j = 0; j < GlobalVars.gridYSize; j++) {
				if (grid[i][j] == GlobalVars.enemyBoardHit)
					enemyButtons[i][j].setBackground(Color.RED);
				else if (grid[i][j] == GlobalVars.enemyBoardMiss)
					enemyButtons[i][j].setBackground(Color.darkGray);

			}

		}
	}

//	private Component NorthPanel() {
//		JPanel panel = new JPanel();
//
//		return panel;
//	}

}
